import { fabric } from 'fabric'
import { ElMessageBox, ElMessage } from 'element-plus'
import { blobToBase64, getStorage, deleteStorage, STORAGE_FABRIC_KEY } from './tools'

/**
 * 左侧图片操作
 * @param {*} canvasRef 
 * @param {*} currentTplId 
 * @returns 
 */
export const useSelectImg = ({
  canvasRef,
  fileList,
  currentTplId,
  dialogImageUrl,
  dialogVisible
}) => {
  // 获取左侧图片
  const initSelectImg = () => {
    const storage = getStorage(STORAGE_FABRIC_KEY)
    fileList.value = Object.keys(storage).map(id => {
      const url = storage[id]?.url ?? ''
      const name = storage[id]?.name ?? ''
      return { id, url, name }
    })
  }
  // 选择图片
  const handleSelect = async (file) => {
    currentTplId.value = file.id ?? ''

    canvasRef.value.clear()
    canvasRef.value.backgroundColor = 'rgba(255, 255, 255, 1)'

    const storage = getStorage(STORAGE_FABRIC_KEY)
    const { id } = file

    if (storage[id]) {
      // const jsonRaw = markRaw(storage[id].json)
      canvasRef.value.loadFromJSON(storage[id].json, canvasRef.value.renderAll.bind(canvasRef.value))
    } else {
      const base64 = await blobToBase64(file.raw)
      fabric.Image.fromURL(base64, (sImg) => {
        sImg.scale(0.3)
        // vue3中会将add的元素转成Proxy，会导致元素控件无法响应，即无法缩放和删除等操作，所以需要使用markRaw将元素标记为原始对象
        const sImgRaw = markRaw(sImg)
        canvasRef.value.add(sImgRaw)
      })
    }
  }

  const handlePictureCardPreview = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url
    dialogVisible.value = true
  }

  const handleRemove = async (uploadFile) => {
    await ElMessageBox.confirm('确定删除该图片吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    fileList.value = fileList.value.filter((file) => file.url !== uploadFile.url)
    deleteStorage(STORAGE_FABRIC_KEY, uploadFile.id)
    ElMessage.success('删除成功')
  }

  return {
    initSelectImg,
    handleSelect,
    handlePictureCardPreview,
    handleRemove,
  }
}
